package com.szzg10.mina2.chapter2;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioDatagramConnector;

/**
 * NioDatagramConnector
 * FilterChain
 * Handler
 * ConnectFuture(IoFutureListener)
 * 
 */
public class UdpClient {

	public static final String HOSTNAME = "127.0.0.1";
	public static final int PORT = 9123;
	
	public static void main(String[] args) {
		NioDatagramConnector connector = new NioDatagramConnector();
		
		connector.getFilterChain().addLast("logger", new LoggingFilter());
		connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
		
		connector.setHandler(new UdpClientHandler());
		
		ConnectFuture future = connector.connect(new InetSocketAddress(HOSTNAME, PORT));
		
		future.addListener(new IoFutureListener<IoFuture>() {

			@Override
			public void operationComplete(IoFuture arg0) {
				
				ConnectFuture tempFuture = (ConnectFuture)arg0;
				if(tempFuture.isConnected()) {
					long freeMemory = Runtime.getRuntime().freeMemory();
					
					IoSession ioSession = tempFuture.getSession();
					ioSession.write(freeMemory);
				}
				
			}
		});
	}
}
